<!DOCTYPE html>
<html lang="en">
<head>
    <title>SSE Client</title>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
</head>
<body>
<div>
    <ul id="messages">
    </ul>
</div>

<script>
    if (window.EventSource == null) {
        alert('The browser does not support Server-Sent Events');
    }

    let streamId = 'test';
    let authorizationToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.KMUFsIDTnFmyG3nMiGM6H9FNFUROf3wh7SmqJp-QV30';
    let targetUrl = `http://localhost:8800/events?stream=${streamId}&token=${authorizationToken}`;

    const eventSource = new EventSource(targetUrl, {withCredentials: false});

    // 在事件源连接未能打开时触发。
    eventSource.onerror = function (error) {
        console.log('connection state: ' + eventSource.readyState + ', error: ' + error);
    };

    // 在与事件源的连接打开时触发。
    eventSource.onopen = function () {
        console.log('connection is established');
    };

    // 在从事件源接收到数据时触发。
    eventSource.onmessage = (event) => {
        console.log('id: ' + event.lastEventId + ', data: ' + event.data);
        //console.log(JSON.parse(event.data))
        const ul = document.getElementById("messages");
        const li = document.createElement("li");
        li.appendChild(document.createTextNode(`${event.data}`));
        li.setAttribute("id", "element4");
        ul.appendChild(li);
    }
</script>
</body>
</html>